package cn.com.ylpw.web.order.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import cn.com.ylpw.web.order.service.PromotionService;
import cn.com.ylpw.web.util.RestTemplateUtil;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;

@Service("promotionService")
public class PromotionServiceImpl implements PromotionService {
	public final Logger log = LoggerFactory.getLogger(getClass());
	
	public static final String PROMOTION_URL="http://promo.228/promo/getPromoByOrder.json"; //促销接口
	@Override
	/**
	 * 
	 * @description 向第三方接口发送xml数据请求
	 * @param xmlData
	 * @return
	 */
	public Map<String,Object> promoHttpClientPost(Map<String,Object> paramMap) {
		
		RestTemplate restTemplate = RestTemplateUtil.getInstance();
		HttpHeaders requestHeaders = new HttpHeaders();
		LinkedMultiValueMap<String,Object> vars = new LinkedMultiValueMap<String, Object>();
		for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
			 vars.add(entry.getKey(),  entry.getValue().toString());
	    }
		HttpEntity<Object> entity = new HttpEntity<Object>(vars, requestHeaders);
		int result;
		String repXml="";
		HashMap<String,Object> repMap = Maps.newHashMap();
		try {
			ResponseEntity<String> responseEntity = restTemplate.postForEntity(PROMOTION_URL, entity, String.class);
			result = responseEntity.getStatusCode().value();
			repXml = responseEntity.getBody();
			repMap.put("result", result);
		    repMap.put("jsonData", repXml);
		} catch (Exception e) {
			log.error("向第三方接口发送xml数据请求失败", e);
		}
        return repMap;
	}
	@Override
	public Map<String, Object> getPromoInfoMap(Map<String, Object> paramMap) {
		Map<String,Object> retMap = this.promoHttpClientPost(paramMap);
		Integer result = (Integer)retMap.get("result");
		if(result != null && result == 200){
			String retJson = (String)retMap.get("jsonData");
			ObjectMapper mapper = new ObjectMapper();
			try {
				Map<String,Object> map= mapper.readValue(retJson, Map.class);
				Map<String,Object> PromoInfosMap = (Map<String,Object>)map.get("data");
				if (PromoInfosMap!= null && PromoInfosMap.size()>0) {
					return PromoInfosMap;
				}else {
					return null;
				}
			} catch (Exception e) {
				 log.error("获取促销信息失败{}",paramMap,e);
				 return null;
			}
		}else{
			return null;
		}
	}

}
